package com.king.controller;


import com.king.common.lang.Result;
import com.king.entity.MComment;
import com.king.entity.MPost;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.king.controller.BaseController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author KING
 * @since 2020-09-01
 */
@Controller
@RequestMapping("/comment")
public class MCommentController extends BaseController {

    @Transactional
    @ResponseBody
    @PostMapping("/delete")
    public Result delete(Long id) {
        Assert.notNull(id, "评论id不能为空！");
        MComment comment = mCommentService.getById(id);
        Assert.notNull(comment, "找不到该评论！");
        if (comment.getUserId() != getProfileId()) {
            return Result.fail("不是你发表的评论！");
        }
        mCommentService.removeById(id);

        MPost post = mPostService.getById(comment.getPostId());
        post.setCommentCount(post.getCommentCount() - 1);
        mPostService.updateById(post);//更新文章评论数

        mPostService.updateCommentCountAndUnionForWeekRank(comment.getPostId(), false);//更新本周热议

        return Result.success();
    }

    /**
     * 点赞评论
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/like")
    public Result like(Long id,Boolean ok) {
        Assert.notNull(id, "评论id不能为空！");
        MComment comment = mCommentService.getById(id);
        Assert.notNull(comment, "找不到该评论！");
        Integer count = comment.getVoteUp()+(ok?-1:1);
        if(count<0){
            count = 0;
        }
        comment.setVoteUp(count);
        mCommentService.updateById(comment);

        return Result.success();
    }
}
